<template>
  <div class="grade-search-page">
    <!-- 页面头部 -->
    <div class="content-header">
      <h1>成绩查询系统</h1>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="学期">
          <el-select v-model="filterForm.semester" placeholder="请选择学期">
            <el-option v-for="item in semesters" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程">
          <el-input v-model="filterForm.course" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="成绩区间">
          <el-input-number v-model="filterForm.minScore" placeholder="最低分" :min="0" :max="100"></el-input-number>
          <span class="mx-2">-</span>
          <el-input-number v-model="filterForm.maxScore" placeholder="最高分" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchGrades">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩表格 -->
    <el-card class="mt-4">
      <div class="flex justify-between items-center mb-4">
        <h3>成绩列表</h3>
        <div class="flex items-center">
          <el-button type="text" @click="exportGrades">导出 Excel</el-button>
          <el-button type="text" @click="refreshGrades">刷新数据</el-button>
        </div>
      </div>

      <el-table 
        :data="displayedGrades" 
        stripe 
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column prop="studentId" label="学号" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="course" label="课程" align="center"></el-table-column>
        <el-table-column prop="semester" label="学期" align="center"></el-table-column>
        <el-table-column prop="score" label="成绩" align="center">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="mini" @click="viewDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalGrades"
        style="margin-top: 20px;"
      ></el-pagination>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="mt-4">
      <h3>成绩统计</h3>
      <el-row :gutter="20">
        <el-col :span="8" v-for="(stat, index) in scoreStats" :key="index">
          <el-card :body-style="{ padding: '10px' }">
            <div class="text-center">
              <p class="text-sm text-gray-500">{{ stat.label }}</p>
              <p class="text-2xl font-bold">{{ stat.value }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog 
      title="成绩详情" 
      :visible.sync="detailDialogVisible" 
      width="40%"
      @close="clearDetailForm"
    >
      <el-form :model="detailForm" label-width="100px">
        <el-form-item label="学号">
          <el-input v-model="detailForm.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="detailForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程">
          <el-input v-model="detailForm.course" disabled></el-input>
        </el-form-item>
        <el-form-item label="学期">
          <el-input v-model="detailForm.semester" disabled></el-input>
        </el-form-item>
        <el-form-item label="成绩">
          <el-input v-model="detailForm.score"></el-input>
        </el-form-item>
        <el-form-item label="评语">
          <el-input type="textarea" v-model="detailForm.comment"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveGradeDetails">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import Mock from 'mockjs';

// 初始化 Vuex store
const store = useStore();
const route = useRoute();
const router = useRouter();

// 定义筛选表单
const filterForm = reactive({
  semester: '',
  course: '',
  minScore: 0,
  maxScore: 100
});

// 学期选项
const semesters = [
  { value: '2023-2024-1', label: '2023-2024学年第一学期' },
  { value: '2023-2024-2', label: '2023-2024学年第二学期' },
  { value: '2024-2025-1', label: '2024-2025学年第一学期' },
  { value: '2024-2025-2', label: '2024-2025学年第二学期' }
];

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalGrades = ref(0);

// 详情弹窗
const detailDialogVisible = ref(false);
const detailForm = reactive({
  studentId: '',
  name: '',
  course: '',
  semester: '',
  score: 0,
  comment: ''
});

// 加载状态
const loading = ref(false);
const refreshTimer = ref(null);

// 🔥 计算属性：根据筛选条件过滤成绩
const filteredGrades = computed(() => {
  const { semester, course, minScore, maxScore } = filterForm;
  
  return store.state.grades.allGrades.filter(grade => {
    const matchesSemester = !semester || grade.semester === semester;
    const matchesCourse = !course || grade.course.includes(course);
    const matchesScore = grade.score >= minScore && grade.score <= maxScore;
    
    return matchesSemester && matchesCourse && matchesScore;
  });
});

// 🔥 计算属性：分页后的数据
const displayedGrades = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  
  return filteredGrades.value.slice(start, end);
});

// 🔥 计算属性：成绩统计信息
const scoreStats = computed(() => {
  const grades = filteredGrades.value;
  const count = grades.length;
  
  if (count === 0) {
    return [
      { label: '平均分', value: '0' },
      { label: '最高分', value: '0' },
      { label: '最低分', value: '0' }
    ];
  }
  
  const sum = grades.reduce((total, grade) => total + grade.score, 0);
  const avg = (sum / count).toFixed(1);
  const max = Math.max(...grades.map(grade => grade.score));
  const min = Math.min(...grades.map(grade => grade.score));
  
  return [
    { label: '平均分', value: avg },
    { label: '最高分', value: max },
    { label: '最低分', value: min }
  ];
});

// 🔥 生命周期钩子：组件挂载时加载数据
onMounted(() => {
  console.log('成绩查询组件已挂载');
  
  // 检查用户权限
  if (!store.state.user.isAdmin) {
    router.push('/home');
    return;
  }
  
  // 加载成绩数据
  fetchGrades();
  
  // 🔥 模拟定时刷新（演示 onUnmounted 清理）
  refreshTimer.value = setInterval(() => {
    console.log('定时刷新数据...');
  }, 30000);
});

// 🔥 生命周期钩子：组件卸载时清理
onUnmounted(() => {
  console.log('成绩查询组件已卸载');
  clearInterval(refreshTimer.value);
});

// 🔥 数据监听：监听筛选条件变化，自动触发查询
watch(filterForm, () => {
  // 重置页码
  currentPage.value = 1;
  // 触发查询（防抖处理）
  const timer = setTimeout(() => {
    updateTotalGrades();
  }, 300);
  
  return () => clearTimeout(timer);
}, { deep: true });

// 获取成绩数据
const fetchGrades = async () => {
  loading.value = true;
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 🔥 使用Vuex action获取成绩数据
    await store.dispatch('grades/fetchAllGrades');
    
    // 更新总数
    updateTotalGrades();
  } catch (error) {
    console.error('获取成绩数据失败:', error);
    ElMessage.error('获取成绩数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 更新总数
const updateTotalGrades = () => {
  totalGrades.value = filteredGrades.value.length;
};

// 搜索成绩
const searchGrades = () => {
  // 重置页码
  currentPage.value = 1;
  // 更新总数
  updateTotalGrades();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.semester = '';
  filterForm.course = '';
  filterForm.minScore = 0;
  filterForm.maxScore = 100;
};

// 处理分页变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 获取成绩样式（根据分数显示不同颜色）
const getScoreClass = (score) => {
  if (score >= 90) return 'text-green-600';
  if (score >= 60) return 'text-blue-600';
  return 'text-red-600';
};

// 查看详情
const viewDetails = (row) => {
  // 填充详情表单
  detailForm.studentId = row.studentId;
  detailForm.name = row.name;
  detailForm.course = row.course;
  detailForm.semester = row.semester;
  detailForm.score = row.score;
  detailForm.comment = row.comment || '';
  
  // 显示弹窗
  detailDialogVisible.value = true;
};

// 保存成绩详情
const saveGradeDetails = () => {
  // 🔥 使用Vuex mutation更新成绩
  store.commit('grades/updateGrade', {
    studentId: detailForm.studentId,
    course: detailForm.course,
    semester: detailForm.semester,
    score: detailForm.score,
    comment: detailForm.comment
  });
  
  // 关闭弹窗
  detailDialogVisible.value = false;
  
  // 提示成功
  ElMessage.success('成绩更新成功');
};

// 清除详情表单
const clearDetailForm = () => {
  detailForm.studentId = '';
  detailForm.name = '';
  detailForm.course = '';
  detailForm.semester = '';
  detailForm.score = 0;
  detailForm.comment = '';
};

// 导出Excel
const exportGrades = () => {
  console.log('导出成绩数据...');
  ElMessage.info('导出功能开发中...');
};

// 刷新数据
const refreshGrades = () => {
  fetchGrades();
  ElMessage.success('数据已刷新');
};

// 处理行点击
const handleRowClick = (row) => {
  viewDetails(row);
};
</script>

<style scoped>
.grade-search-page {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.mx-2 {
  margin-left: 8px;
  margin-right: 8px;
}

.text-sm {
  font-size: 12px;
}

.text-gray-500 {
  color: #6c757d;
}

.text-2xl {
  font-size: 24px;
}

.font-bold {
  font-weight: bold;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}
</style>